package com.samoilovich.belarustoday.handlers;

import android.util.Log;

import com.samoilovich.belarustoday.afisha.films.FilmsFragment;
import com.samoilovich.belarustoday.afisha.films.SeancesFragment;
import com.samoilovich.belarustoday.afisha.fragments.EventFragment;
import com.samoilovich.belarustoday.datemodel.CinemaModel;
import com.samoilovich.belarustoday.datemodel.EventModel;
import com.samoilovich.belarustoday.datemodel.FilmModel;
import com.samoilovich.belarustoday.datemodel.SeanceModel;
import com.samoilovich.belarustoday.tools.Utility;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;

public class AfishaContentHandler {
    private final String TAG = getClass().getName();

    private final String GET_FILMS_LIST_URL = "http://belarustoday.by/belarus/api/getfilms.php?day=%s";
    private final String GET_SEANCES_LIST_URL = "http://belarustoday.by/belarus//api/getseance.php?film=%s&day=%s";
    private final String GET_EVENTS_LIST_URL = "http://belarustoday.by/belarus/api/getevents.php?event_type=%s&day=%s";

    private final String FILM_ID = "film_id";
    private final String FILM_DESCRIPTION = "film_description";
    private final String FILM_NAME = "film_name";
    private final String FILM_POSTER = "film_poster";
    private final String FILM_AGE_LIMIT = "film_age_limit";
    private final String FILM_GANRY = "film_ganry";
    private final String FILM_YEAR = "film_year";
    private final String FILM_COUNTRY = "film_country";
    private final String FILM_DIRECTOR = "film_director";
    private final String FILM_LINK = "film_link";
    private final String FILM_TIME = "film_time";
    private final String FILM_DAY_LIST ="film_day_list";

    private final String PROPERTY = "property";
    private final String CINEMA_ID = "cinema_id";
    private final String CINEMA_NAME = "cinema_name";
    private final String CINEMA_PLACE = "cinema_place";
    private final String CINEMA_PHONE = "cinema_phone";
    private final String CINEMA_METRO = "cinema_metro";
    private final String CINEMA_LINK = "cinema_link";
    private final String CINEMA_LATITUDE = "cinema_latitude";
    private final String CINEMA_LONGITUDE = "cinema_longitude";
    private final String SEANCE = "seance";

    private final String EVENT_NAME = "event_name";
    private final String EVENT_TIME = "event_time";
    private final String EVENT_IMAGE = "event_image";
    private final String EVENT_PLACE_NAME = "event_place_name";
    private final String EVENT_PLACE_LINK = "event_place_link";
    private final String EVENT_LINK = "event_link";
    private final String EVENT_DESCRIPTION = "event_description";
    private final String EVENT_TYPE = "event_type";
    private final String EVENT_DAY = "event_day";

    private ArrayList<FilmModel> mFilms;
    private ArrayList<SeanceModel> mSeances;
    private ArrayList<EventModel> mEvents;

    private static AfishaContentHandler sInstance;

    public static AfishaContentHandler getInstance() {
        if (sInstance == null) {
            sInstance = new AfishaContentHandler();
        }

        return sInstance;
    }

    private AfishaContentHandler() {

    }

    public void getFilmsList(final FilmsFragment listener, final String date) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpResponse response;
                HttpClient client;
                HttpParams params;

                try {
                    params = Utility.createHttpParams();
                    client = new DefaultHttpClient(params);
                    response = client.execute(new HttpGet(String.format(GET_FILMS_LIST_URL, date)));
                    InputStream stream = response.getEntity().getContent();
                    String json = Utility.convertStreamToString(stream);
                    parseFilmsJSON(json);
                    listener.updateFilmsList(mFilms);
                    Log.d(TAG, json);
                } catch (Exception exp) {
                    exp.printStackTrace();
                }
            }
        }).start();
    }

    public void getSeancesList(final SeancesFragment listener, final String filmsId, final String date) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpResponse response;
                HttpClient client;
                HttpParams params;

                try {
                    params = Utility.createHttpParams();
                    client = new DefaultHttpClient(params);
                    response = client.execute(new HttpGet(String.format(GET_SEANCES_LIST_URL, filmsId, date)));
                    InputStream stream = response.getEntity().getContent();
                    String json = Utility.convertStreamToString(stream);
                    parseSeancesJSON(json);
                    listener.updateSeancesList(mSeances);
                    Log.d(TAG, json);
                } catch (Exception exp) {
                    exp.printStackTrace();
                }
            }
        }).start();
    }

    public void getEventList(final EventFragment listener, final long eventType, final String date) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpResponse response;
                HttpClient client;
                HttpParams params;

                try {
                    params = Utility.createHttpParams();
                    client = new DefaultHttpClient(params);
                    response = client.execute(new HttpGet(String.format(GET_EVENTS_LIST_URL, eventType + "", date)));
                    InputStream stream = response.getEntity().getContent();
                    String json = Utility.convertStreamToString(stream);
                    parseEventsJSON(json);
                    listener.updateEventList(mEvents);
                    Log.d(TAG, json);
                } catch (Exception exp) {
                    exp.printStackTrace();
                }
            }
        }).start();
    }

    // -----------------------------------------------------------------------------------
    // -----------------------------------------------------------------------------------
    private void parseFilmsJSON(String json) {
        JSONObject temp;
        FilmModel film;
        JSONArray jsonDayList;
        ArrayList<String> dayList;

        try {
            mFilms = new ArrayList<FilmModel>();
            JSONArray array = new JSONArray(json);
            for (int i = 0; i < array.length(); i++) {
                film = new FilmModel();
                temp = array.getJSONObject(i);
                film.setId(temp.getString(FILM_ID));
                film.setDescription(temp.getString(FILM_DESCRIPTION));
                film.setName(temp.getString(FILM_NAME));
                film.setPoster(temp.getString(FILM_POSTER));
                film.setAgeLimit(temp.getString(FILM_AGE_LIMIT));
                film.setGenre(temp.getString(FILM_GANRY));
                film.setYear(temp.getString(FILM_YEAR));
                film.setCountry(temp.getString(FILM_COUNTRY));
                film.setDirector(temp.getString(FILM_DIRECTOR));
                film.setLink(temp.getString(FILM_LINK));
                film.setTime(temp.getString(FILM_TIME));
                jsonDayList = temp.getJSONArray(FILM_DAY_LIST);
                dayList = new ArrayList<String>();
                for (int j = 0; j < jsonDayList.length(); j++) {
                    dayList.add(jsonDayList.getString(j));
                }
                film.setDayList(dayList);
                mFilms.add(film);
            }

        } catch (Exception exp) {
            exp.printStackTrace();
        }
    }

    private void parseSeancesJSON(String json) {
        JSONObject temp, cinemaObj;
        JSONArray seancesArray;
        SeanceModel seance;
        CinemaModel cinema;

        try {
            mSeances = new ArrayList<SeanceModel>();
            JSONArray array = new JSONArray(json);
            for (int i = 0; i < array.length(); i++) {
                cinema = new CinemaModel();
                temp = array.getJSONObject(i);
                cinemaObj = temp.getJSONObject(PROPERTY);
                cinema.setId(cinemaObj.getString(CINEMA_ID));
                cinema.setName(cinemaObj.getString(CINEMA_NAME));
                cinema.setPlace(cinemaObj.getString(CINEMA_PLACE));
                cinema.setPhone(cinemaObj.getString(CINEMA_PHONE));
                cinema.setMetro(cinemaObj.getString(CINEMA_METRO));
                cinema.setLink(cinemaObj.getString(CINEMA_LINK));
                cinema.setLatitude(cinemaObj.getString(CINEMA_LATITUDE));
                cinema.setLongitude(cinemaObj.getString(CINEMA_LONGITUDE));
                seance = new SeanceModel();
                seance.setIsCinemaInfo(true);
                seance.setCinema(cinema);
                mSeances.add(seance);
                seancesArray = temp.getJSONArray(SEANCE);
                for (int j = 0; j < seancesArray.length(); j++) {
                    seance = new SeanceModel();
                    seance.setIsCinemaInfo(false);
                    seance.setTime(seancesArray.get(j).toString());
                    mSeances.add(seance);
                }
            }

        } catch (Exception exp) {
            exp.printStackTrace();
        }
    }

    private void parseEventsJSON(String json) {
        JSONObject temp;
        EventModel event;

        try {
            mEvents = new ArrayList<EventModel>();
            JSONArray array = new JSONArray(json);
            for (int i = 0; i < array.length(); i++) {
                event = new EventModel();
                temp = array.getJSONObject(i);
                event.setName(temp.getString(EVENT_NAME));
                event.setTime(temp.getString(EVENT_TIME));
                event.setImage(temp.getString(EVENT_IMAGE));
                event.setPlaceName(temp.getString(EVENT_PLACE_NAME));
                event.setPlaceLink(temp.getString(EVENT_PLACE_LINK));
                event.setEventLink(temp.getString(EVENT_LINK));
                event.setEventDescription(temp.getString(EVENT_DESCRIPTION));
                event.setEventType(temp.getString(EVENT_TYPE));
                event.setEventDay(temp.getString(EVENT_DAY));
                mEvents.add(event);
            }

        } catch (Exception exp) {
            exp.printStackTrace();
        }
    }
}
